package com.leapp.sk.view.im

import android.app.Activity
import android.content.Context
import android.os.Handler
import android.os.Message
import android.support.v4.content.ContextCompat
import android.support.v4.widget.SwipeRefreshLayout
import android.text.TextUtils
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.ListView
import android.widget.RelativeLayout
import cc.vv.lkimcomponent.lkim.bean.LKIMMessage
import cc.vv.lkimcomponent.lkim.inter.LKIMMessageInter
import cc.vv.lkimcomponent.lkim.operate.LKIMGet
import com.example.mvp.view.CabcelSureDialog
import com.example.util.RECERVE_USER_ID
import com.leapp.sk.R
import com.example.util.inter.MsgUpdateInterface
import com.leapp.sk.ui.adapter.SingleChatAdapter
import com.example.util.im.MessagePresenter
import com.leapp.sk.app.SKApplication
import com.example.util.finallist.*


/**
 * 消息内容列表自定义View
 * @author  chaohaipeng  on 2018/7/12.
 */
class SKChatMessageList : RelativeLayout, MsgUpdateInterface, SwipeRefreshLayout.OnRefreshListener {


    /**
     * 数据
     */
    val mList = mutableListOf<LKIMMessage>()
    /**
     * 消息列表
     */
    var listView: ListView? = null
    /**
     * 刷新控件
     */
    var swipeRefreshLayout: SwipeRefreshLayout? = null
    /**
     * 上下文
     */
    var mContext: Activity? = null
    /**
     * 消息类别
     */
    var chatType: Int = 0
    /**
     * 用户名
     */
    var toChatUsername: String = ""
    /**
     * 消息适配器
     */
    var mAdapter: SingleChatAdapter? = null

    private var mLoadNum: Int = 0
    private var mAccount: String = RECERVE_USER_ID
    /**
     * 是否正在刷新
     */
    private var isRefresh: Boolean = false


    /**
     * dialog
     */
    private var cabcelSureDialog: CabcelSureDialog? = null

    constructor(context: Context) : super(context) {
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
    }




    /**
     * 消息适配器
     */
    var mHandler: Handler = Handler(object : Handler.Callback {
        override fun handleMessage(message: Message?): Boolean {
            when (message?.what) {
            /**
             * 插入一条消息
             */
                SK_200 -> {
                    val bundle = message?.data
                    val lkImMessage = bundle?.getParcelable<LKIMMessage>(IM_MESSAGE)
                    if (!TextUtils.equals(mAccount, lkImMessage?.toAccount)) {
                        return false
                    }
                    if (lkImMessage != null) {
                        mList.add(lkImMessage)
                        Handler().postDelayed(object : Runnable {
                            override fun run() {
                                val count = mAdapter?.count?.minus(1)
                                if (count != null) {
                                    listView?.setSelection(count)
                                }
                            }
                        }, 100)
                        mAdapter?.notifyDataSetChanged()
                    }
                }
            //消息状态改变
                SK_201 -> {
                    val bundle = message?.data
                    val messigeId = bundle?.getString(IM_MESSAGE_ID)
                    val lkImMessage = bundle?.getParcelable<LKIMMessage>(IM_MESSAGE)
                    if (!TextUtils.equals(mAccount, lkImMessage?.toAccount)) {
                        return false
                    }
                    if (lkImMessage != null) {
                        for (i in mList.indices) {
                            var get = mList.get(i)
                            if (TextUtils.equals(get.msgId, messigeId)) {
                                get = lkImMessage
                                break
                            }
                        }
                        SKApplication.getInstance()?.mHandler?.postDelayed(object : Runnable {
                            override fun run() {
                                val count = mAdapter?.count?.minus(1)
                                if (count != null) {
                                    listView?.setSelection(count)
                                }
                            }
                        }, 100)

                        mAdapter?.notifyDataSetChanged()
                    }
                }
            //消息撤回
                SK_202 -> {
                    val bundle = message?.data
                    val messigeId = bundle?.getString(IM_MESSAGE_ID)
                    val lkImMessage = bundle?.getParcelable<LKIMMessage>(IM_MESSAGE)
                    if (!TextUtils.equals(mAccount, lkImMessage?.toAccount)) {
                        return false
                    }
                    if (lkImMessage != null) {
                        for (i in mList.indices) {
                            var get = mList.get(i)
                            if (TextUtils.equals(get.msgId, messigeId)) {
                                mList.remove(get)
                                break
                            }
                        }
                        mList.add(lkImMessage)
                        mAdapter?.notifyDataSetChanged()
                    }
                }
            //删除消息
                SK_203 -> {
                    val bundle = message?.data
                    val messigeId = bundle?.getString(IM_MESSAGE_ID)
                    for (i in mList.indices) {
                        var get = mList.get(i)
                        if (TextUtils.equals(get.msgId, messigeId)) {
                            mList.remove(get)
                            break
                        }
                    }
                    mAdapter?.notifyDataSetChanged()
                }
            }
            return false
        }

    })


    override fun onRefresh() {
        isRefresh = true
        mHandler.postDelayed(object : Runnable {
            override fun run() {
                if (mList != null && mList.size > 0) {
                    val get = mList.get(0)
                    loadMessage(mAccount!!, get.msgId, 20)
                }
            }
        }, 500)
    }

    /**
     * 加载消息
     *
     * @param startMessageId 开始消息id,传null则从第一条开始加载
     * @param loadNum        加载条数
     */
    fun loadMessage(mAccount: String, startMessageId: String, loadNum: Int) {
        val size = if (-1 == loadNum) 20 else loadNum
        LKIMGet.getInstance().getMoreMessage(mAccount, startMessageId, size, object : LKIMMessageInter {
            override fun success(lkimMessages: List<LKIMMessage>?) {
                if (null != lkimMessages && !lkimMessages.isEmpty()) {
                    swipeRefreshLayout?.isRefreshing = false
                    mList.addAll(0, lkimMessages)
                    mAdapter?.notifyDataSetChanged()
                    if (mLoadNum != -1) {
                        mHandler?.postDelayed({
                            val count = mAdapter?.count?.minus(1)
                            if (count != null) {
                                listView?.setSelection(count)
                            }
                            mLoadNum = -1
                        }, 500)

                    } else if (!TextUtils.isEmpty(startMessageId)) {
                        listView?.setSelection(lkimMessages.size)
                    }

                }
            }

            override fun faile() {
                swipeRefreshLayout?.isRefreshing = false
            }
        })
    }

    /**
     * 初始化布局
     */
    fun init(context: Activity, account: String) {
        mAccount = account
        mContext = context
        val view = LayoutInflater.from(context).inflate(R.layout.sk_chat_message_list, this)
        swipeRefreshLayout = view.findViewById(R.id.srl_chat_swipe_layout)
        listView = view.findViewById(R.id.lv_chat_list)
        mAdapter = SingleChatAdapter(context, mList)
        listView?.adapter = mAdapter
        swipeRefreshLayout?.setOnRefreshListener(this)
        swipeRefreshLayout?.setColorSchemeColors(ContextCompat.getColor(mContext, R.color.color_19AD19))
        cabcelSureDialog = CabcelSureDialog(mContext, com.example.baselibrary.R.style.dialog_style)
        initEvent()
    }

    /**
     * 初始化事件
     */
    fun initEvent() {
//        listView?.setOnItemClickListener { adapterView, view, i, l ->
//            val get = mList.get(i)
//            if (get.lkimChatType == LKIMChatType.GroupChat) {
//                val unReadMemberIds = get.getAttribute(IMExtKey.EXTKEY_UNREADMEMBERIDS, "")
//                val readMemberIds = get.getAttribute(IMExtKey.EXTKEY_READMEMBERIDS, "")
//                val intent = Intent(mContext, MessageStateActivity::class.java)
//                intent.putExtra(READ_MESSAGE_IDS, readMemberIds)
//                intent.putExtra(UNREAD_MESSAGE_IDS, unReadMemberIds)
//                intent.putExtra(GROUP_ID, get.toAccount)
//                mContext?.startActivity(intent)
//            }
//        }
//        listView?.setOnItemLongClickListener { adapterView, view, i, l ->
//            val get = mList.get(i)
//            longClickEvent(get)
//            true
//        }
    }




    /**
     * 撤销提醒
     */
    private fun imWithdrawInform(mIMMessage: LKIMMessage) {
        cabcelSureDialog?.setDialogContent(mContext?.resources?.getString(R.string.string_im_withdraw_mesg))
        cabcelSureDialog?.setDialogConfirm(mContext?.resources?.getString(R.string.string_login_dialog_ok))
        cabcelSureDialog?.setEventInterface(object : CabcelSureDialog.DialogEventInterface {
            override fun leftOnClick() {
                cabcelSureDialog?.cancel()
            }

            override fun rightOnClick() {
                cabcelSureDialog?.cancel()
               // imWithdraw(mIMMessage)
            }
        })
        cabcelSureDialog?.show()
    }

    /**
     * 消息更新监听初始化
     */
    fun initMegListener(messagePresenter: MessagePresenter) {
        messagePresenter.msgUpdateInterfaceListener(this)

    }

    override fun updateMsg(message: Message) {
        val message1 = Message()
        message1.what=message.what
        message1.data=message.data
        mHandler.sendMessage(message1)

    }


}